import { createStore, Store, useStore as useVuexStore } from 'vuex'
import type { IRootState, IStoreType } from './type'
import login from './login/login'
import system from './main/system/system'
import story from './main/story/story'
import { getPageListData } from '../service/main/sysytem/system'
import dashboard from './main/analysis/dashboard'

const store = createStore<IRootState>({
  state: () => {
    return {
      entireDeparment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  mutations: {
    changeEntireDepartment(state, list) {
      state.entireDeparment = list
    },
    changeEntireRole(state, list) {
      state.entireRole = list
    },
    changeEntireMenu(state, list) {
      state.entireMenu = list
    }
  },
  getters: {},
  actions: {
    async getInitialDataAction({ commit }) {
      const departmentRes = await getPageListData('/department/list', {
        offset: 0,
        size: 100
      })

      const { list: departmentList } = departmentRes.data
      const roleList = await getPageListData('/role/list', {
        offset: 0,
        size: 100
      })
      const { list: RoleList } = roleList.data
      const menuRes = await getPageListData('/menu/list', {})
      const { list: menuList } = menuRes.data
      commit('changeEntireMenu', menuList)
      commit('changeEntireDepartment', departmentList)
      commit('changeEntireRole', RoleList)
    }
  },
  modules: {
    login,
    system,
    dashboard,
    story
  }
})

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
  // store.dispatch('getInitialDataAction')
}

export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
